# -*- coding: utf-8 -*-

"""
Create and delete a entry in the windows explorer context menu.
"""

import win32api
import win32con
import pywintypes

def get_base():
    handle = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, "Software\\Classes")
    return handle

def install(extensions, context_name, command):
    assert isinstance(extensions, (list, tuple))

    def _install(ext):
        key = "%s\shell\%s" % (ext, context_name)
        print "Create: '%s'" % key
        # Creates the specified key, or opens the key if it already exists.
        base = get_base()
        reg_key = win32api.RegCreateKey(base, key)

        try:
            win32api.RegSetValue(reg_key, "command", win32con.REG_SZ, command)
        except pywintypes.error, err:
            msg = "%s - Try to run this as a Administrator!" % err
            raise pywintypes.error(msg)

        win32api.RegCloseKey(reg_key)

    for ext in extensions:
        _install(ext)




def deinstall(extensions, context_name):
    assert isinstance(extensions, (list, tuple))

    def _deinstall(ext):
        key = "%s\shell" % ext
        print "Delete: '%s\%s'" % (key, context_name)
        base = get_base()
        handle = win32api.RegOpenKey(base, key)

        try:
            win32api.RegDeleteTree(handle, context_name)
        except pywintypes.error, err:
            no = err.args[0]
            if no == 2:
                # Regkey doesn't exist
                print "Info: %s" % err
                return
            else:
                raise

        win32api.RegCloseKey(handle)

    for ext in extensions:
        _deinstall(ext)



if __name__ == '__main__':
    import os

    from win32com.shell import shell
    print "shell.IsUserAnAdmin:", shell.IsUserAnAdmin()
    print

    extensions = ["AllFileSystemObjects"]# "*", "Folder"
    context_name = "*** a test entry ***"
    command = "notepad.exe '%s'" % os.path.abspath(__file__)

    print "Create a rest entry into the context menu"
    install(extensions, context_name, command)

    print
    raw_input("Check context menu in explorer, than press ENTER.")
    print

    print "Delete the context entry"
    deinstall(extensions, context_name)

    print "-- END --"